#include "UdpSession.h"

namespace mp_net
{

	UdpSession::UdpSession(spIoService ioService) : 
		Threaded(), RecursiveLockingMutex(), m_ioService(ioService),
		m_socket(*m_ioService)
	{
		m_id = MPN_UDP_NO_ID; //Unsigned ID
		m_totalPlayers = 0;

	}

	UdpSession::~UdpSession()
	{
		//Lock
		while(!TryLock()){Sleep(1);}

		//Join worker thread
		Stop(true);

		Unlock();
	}



	std::size_t UdpSession::ReadDataFromSocket(
		char* inputBuffer, udp::endpoint& sender, 
		const int bufferMax, const int index)
	{
		try
		{
			//Read in data.
			std::size_t size =
			m_socket.receive_from(
				boost::asio::buffer(
					inputBuffer,
					bufferMax), 
				sender);
			return size;

			class Gogo{};
			Gogo* gos = new Gogo[12];
			
			std::size_t sizex =
			m_socket.receive_from(
				boost::asio::buffer(
					gos,
					12), 
				sender);
		}
		catch(boost::exception const& ex)
		{
			throw "Error Reading UDP Data";
		}
	}

	void UdpSession::WriteDataToSocket(
		char* data, const udp::endpoint& target, 
		const int bufferMax, const int index)
	{
		try
		{
			//Send data
			m_socket.send_to(
				boost::asio::buffer(
					data, bufferMax),
				target);
			//Clear data
			data[0] = MPN_UDP_PKT_SPECIAL_BYTE;
			data[1] = MPN_UDP_PKT_END_DATA;

		}
		catch(boost::exception const& ex)
		{
			//
			throw "Error Writing UDP Data";
		}
	}


}